package com.chalk.config.security.filter;

import com.chalk.config.security.CustomAuthExceptionEntryPoint;
import com.chalk.config.security.JwtRedisUtil;
import com.chalk.config.security.JwtTokenUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Collections;

/**
 * @date: 2019-04-01 下午 07:03
 * @author: zhaobo0119@outlook.com
 * @Descriptopn:
 */
public class JwtBasicAuthFilter extends BasicAuthenticationFilter {

    private JwtRedisUtil jwtRedisUtil;


    public JwtBasicAuthFilter(AuthenticationManager authenticationManager, JwtRedisUtil jwtRedisUtil, CustomAuthExceptionEntryPoint authExceptionEntryPoint) {
        super(authenticationManager,authExceptionEntryPoint);
        this.jwtRedisUtil = jwtRedisUtil;
    }



    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        String tokenHeader = request.getHeader(JwtTokenUtils.TOKEN_HEADER);
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
            chain.doFilter(request, response);
            return;
        }

        /*---------------------------------------------------------------------------*/
        String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
        String username = JwtTokenUtils.getUsername(token);
        if (StringUtils.isEmpty(username)) {
            super.getAuthenticationEntryPoint().commence(request, response, new UsernameNotFoundException("token error"));
            return;
        }
        if (!jwtRedisUtil.existRedisToke(username)) {
            super.getAuthenticationEntryPoint().commence(request, response, new CustomTokenInvalidException("not login"));
            return;
        }
        String redisToke = jwtRedisUtil.getRedisToke(username);
        if (!token.equals(redisToke)) {
            super.getAuthenticationEntryPoint().commence(request, response, new CustomTokenInvalidException("token invalid"));
            return;
        }
        /*---------------------------------------------------------------------------*/

        // 如果请求头中有token，则进行解析，并且设置认证信息
        SecurityContextHolder.getContext().setAuthentication(this.getAuthentication(token,username));
        chain.doFilter(request, response);
        return;

    }

    /**
     * 这里从token中获取用户信息并新建一个token
     *
     * @param token
     * @param username
     * @return
     */
    private UsernamePasswordAuthenticationToken getAuthentication(String token,String username){
        String role = JwtTokenUtils.getUserRole(token);
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(role)) {
            return new UsernamePasswordAuthenticationToken(username, null, Collections.singleton(new SimpleGrantedAuthority(role)));
        }
        return null;
    }
}
